package com.eip.zd.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eip.zd.common.JwtTokenUtils;
import com.eip.zd.entity.User;
import com.eip.zd.exception.CustomException;
import com.eip.zd.mapper.UserMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserService {
    @Resource
    private UserMapper userMapper;

    public User getUserById(String userId) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return userMapper.selectOne(wrapper);
    }

    public String login(String userId, String password) {
        if (StrUtil.hasEmpty(userId)) {
            throw new CustomException(500, "员工号不能为空");
        }
        User user = getUserById(userId);
        boolean equals = StrUtil.equals(user.getPassword(), password);
        if (!equals) {
            throw new CustomException(500, "账号或者密码错误");
        }
        String token = JwtTokenUtils.getToken(user.getUserId(), user.getPassword());
        return token;
    }

    public void add(User user) {
        if (StrUtil.hasEmpty(user.getUserId())) {
            throw new CustomException(500, "员工号不能为空");
        }
        if (getUserById(user.getUserId()) != null) {
            throw new CustomException(500, "该用户已存在");
        }
        if (StrUtil.hasEmpty(user.getPassword())) {
            user.setPassword("111111");
        }
        userMapper.insert(user);
    }

    public void update(User user) {
        if (StrUtil.hasEmpty(user.getUserId())) {
            throw new CustomException(500, "员工号不能为空");
        }
        if (StrUtil.hasEmpty(user.getPassword())) {
            user.setPassword("111111");
        }
        userMapper.updateById(user);
    }

    public List<User> getUserList(String keyword) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like(keyword != null, "name", keyword).or().eq(keyword != null, "user_id", keyword);
        return userMapper.selectList(wrapper);
    }


    public void remove(Long id) {
        userMapper.deleteById(id);
    }
}
